package com.qls.mt.biz.data.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qls.core.constant.Constant;
import com.qls.core.dto.HtDailyRoom;
import com.qls.core.dto.InitBody;
import com.qls.core.dto.PushHotelBody;
import com.qls.core.entity.*;
import com.qls.core.utils.DateUtils;
import com.qls.mt.biz.common.service.*;
import com.qls.mt.biz.common.utils.FxBaseApiRequest;
import com.qls.mt.biz.common.utils.MtClient;
import com.qls.mt.biz.data.pojo.*;
import com.qls.mt.biz.data.pojo.hotel.BaseInfo;
import com.qls.mt.biz.data.pojo.hotel.HotelDetails;
import com.qls.mt.biz.data.pojo.price.GoodsPrices;
import com.qls.mt.biz.data.pojo.price.PriceModels;
import com.qls.mt.biz.data.pojo.room.RealRoomBaseInfo;
import com.qls.mt.biz.data.pojo.room.RoomBedInfoList;
import com.qls.mt.biz.data.pojo.room.realRoomInfo;
import com.qls.mt.biz.data.pojo.rp.*;
import com.qls.mt.biz.data.pojo.status.GoodsStatus;
import com.qls.mt.biz.data.pojo.status.GoodsStatuses;
import com.qls.mt.biz.data.service.InsertHtService;
import com.qls.rabbitmq.SendMsg;
import com.qls.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class InsertHtServiceImpl implements InsertHtService {

    @Autowired
    private HtHotelinfoService htHotelinfoService;

    @Autowired
    private HtLogicRoomService htLogicRoomService;

    @Autowired
    private HtPhysicalRoomService htPhysicalRoomService;

    @Autowired
    private DtOrderChannelsService dtOrderChannelsService;

    @Autowired
    private RedisUtil redisUtil;

    private Long maxIds = 0L;


    @Autowired
    private OpTaskStatusService opTaskStatusService;

    @Autowired
    private SendMsg sendMsg;


    @Override
    public void insertHtHotelinfo(PushHotelBody pushHotelBody, Map<String, Object> map) {
        //请求参数
        JSONObject data = new JSONObject();
        ArrayList<Long> hotelIds = new ArrayList<>();
        hotelIds.add(pushHotelBody.getHotelId());
        data.put("hotelIds", hotelIds);
        data.put("strategy", 1);
        //接收返回值
        String res = result(data, "hotel.detail", map);
        if ("{\"hotelDetails\":[]}".equals(res)) {
            return;
        }
        Hotel hotel = JSONObject.parseObject(res, Hotel.class);
        if (Objects.isNull(hotel)) {
            return;
        }
        List<HotelDetails> hotelDetailsList = hotel.getHotelDetails();
        if (hotelDetailsList.isEmpty()) {
            return;
        }
        //将返回值转换成BaseInfo对象
        BaseInfo baseInfo = JSONObject.parseObject(res, Hotel.class).getHotelDetails().get(0).getBaseInfo();
        if (Objects.isNull(baseInfo)) {
            return;
        }
        //创建HtHotelinfo对象并赋值
        HtHotel htHotelinfo = new HtHotel();
        //	酒店ID
        htHotelinfo.setHotelCode(baseInfo.getHotelId());
        htHotelinfo.setId(baseInfo.getHotelId());
        //	酒店名称
        htHotelinfo.setHotelName(baseInfo.getPointName());
        //	酒店地址
        String address = baseInfo.getAddress();
        htHotelinfo.setPartnerId(Integer.valueOf(map.get("partnerId").toString()));
        htHotelinfo.setAddress(address.length() < 299 ? address : address.substring(0, 299));
        //城市ID与城市名、城市行政区ID与行政区名的映射关系列表请联系分销平台获取
        htHotelinfo.setProvince(baseInfo.getCityLocationId());
        //城市行政区ID
        htHotelinfo.setDistrict(baseInfo.getLocationId());
        //城市ID
        htHotelinfo.setCity(baseInfo.getCityLocationId());
        //酒店所在商圈名
        String phone = baseInfo.getPhone();
        if (StringUtils.isBlank(phone)) {
            return;
        }
        if (phone.contains(";")) {
            htHotelinfo.setPhone(phone.split(";")[0]);
        }
        if (phone.contains(",")) {
            htHotelinfo.setPhone(phone.split(",")[0]);
        }
        if (phone.length() > 30) {
            htHotelinfo.setPhone(phone.substring(0, 29));
        }
        htHotelinfo.setPhone(phone);
        //酒店营业状态：0 营业中,1 已关门,2 筹建中,3 暂停营业
        Integer status = baseInfo.getCloseStatus();
        if (Objects.isNull(status) || !status.equals(0)) {
            status = -2;
        } else {
            status = 0;
        }
        htHotelinfo.setHotelStatus(status);
        //将数据添加到数据库
        htHotelinfoService.saveOrUpdate(htHotelinfo);
    }

    @Override
    public List<Long> insertHtPhyicalRoom(PushHotelBody pushHotelBody, Map<String, Object> map) {
        //创建列表
        List<Long> listRoomIds = new ArrayList<>();
        List<HtRoomType> htPhysicalRooms = new ArrayList<>();
        //请求参数
        JSONObject data = new JSONObject();
        ArrayList<Long> hotelIds = new ArrayList<>();
        hotelIds.add(pushHotelBody.getHotelId());
        data.put("hotelIds", hotelIds);
        //接收返回值
        String res = result(data, "hotel.realroom.info", map);
        if ("{}".equals(res)) {
            return listRoomIds;
        }
        //将返回值转换成BaseInfo对象
        Map<Long, List<realRoomInfo>> baseInfo = JSONObject.parseObject(res, Room.class).getRealRoomInfos();
        //创建HtHotelinfo对象并赋值
        if (baseInfo.isEmpty()) {
            return listRoomIds;
        }
        for (List<realRoomInfo> real : baseInfo.values()) {
            for (realRoomInfo roomInfo : real) {
                RealRoomBaseInfo realRoomBaseInfo = roomInfo.getRealRoomBaseInfo();
                String roomName = realRoomBaseInfo.getRoomName();
                Integer status = realRoomBaseInfo.getStatus();
                if (Objects.isNull(roomName) || "".equals(roomName) || !status.equals(1)) {
                    continue;
                }
                String regEx = "\\(.*\\)|\\[.*\\]|\\（.*\\）|\\【.*\\】|\\(.*\\）|\\（.*\\)";
                roomName = roomName.replaceAll(regEx, "");
                HtRoomType htPhysicalRoom = new HtRoomType();
                //酒店ID。
                htPhysicalRoom.setHotelCode(pushHotelBody.getHotelId());
                //物理房型ID。
                Long roomCode = realRoomBaseInfo.getRealRoomId();
                htPhysicalRoom.setRoomCode(roomCode);
                listRoomIds.add(roomCode);
                htPhysicalRoom.setId(roomCode);
                //	房型名称, 可能为空
                htPhysicalRoom.setRoomName(roomName.length() < 599 ? roomName : roomName.substring(0, 599));
                //	房间最大容纳人数, 可能为空
                htPhysicalRoom.setMaxNum(realRoomBaseInfo.getCapacity() == null ? "NONE" : realRoomBaseInfo.getCapacity());
                //	房间可用面积, 可能为空
                htPhysicalRoom.setRoomSize(realRoomBaseInfo.getUseableArea() == null ? "NONE" : realRoomBaseInfo.getUseableArea());
                //	房间所在楼层
                htPhysicalRoom.setRoomFloor(realRoomBaseInfo.getFloor() == null ? "NONE" : realRoomBaseInfo.getFloor());
                //	房型状态：0无效, 1 有效  数据库：房型状态。0:正常，-1:删除，-2:停售
                htPhysicalRoom.setRoomStatus(0);
                //	房间最大容纳儿童人数
                List<List<RoomBedInfoList>> listList = roomInfo.getRoomBedInfoList();
                if (Objects.nonNull(listList)) {
                    for (List<RoomBedInfoList> lists : listList) {
                        if (lists.size() != 0) {
                            RoomBedInfoList roomBedInfoList = lists.get(0);
                            //床型类型，如"超级大床"、
                            String bedType = roomBedInfoList.getBedType();
                            htPhysicalRoom.setBedType(bedType.length() < 29 ? bedType : bedType.substring(0, 29));
                            String bedDesc = roomBedInfoList.getBedDesc();
                            //床型描述，如"1.5x2.0米"
                            htPhysicalRoom.setBedWidth(bedDesc.length() < 29 ? bedDesc : bedDesc.substring(0, 29));
                        }
                    }
                }
                htPhysicalRooms.add(htPhysicalRoom);
            }
        }
        if (htPhysicalRooms.size() != 0) {
            htPhysicalRoomService.saveOrUpdateBatch(htPhysicalRooms);
        }
        return listRoomIds;
    }


    @Override
    public List<Long> insertLogicRoom(PushHotelBody pushHotelBody, List<Long> listRoom, Map<String, Object> map) {
        List<Long> rpCodes = new ArrayList<>();
        if (listRoom.isEmpty()) {
            return rpCodes;
        }
        //创建列表
        List<HtSellRoom> htLogicRooms = new ArrayList<>();
        //请求参数
        JSONObject data = new JSONObject();
        ArrayList<Long> hotelIds = new ArrayList<>();
        //获取当前日期
        hotelIds.add(pushHotelBody.getHotelId());
        Map<String, Object> mapDate = date();
        data.put("hotelIds", hotelIds);
        data.put("checkinDate", mapDate.get("startDate"));
        data.put("checkoutDate", mapDate.get("endDate"));
        data.put("goodsType", 1);
        //接收返回值
        String res = result(data, "hotel.goods.rp", map);
        if ("{}".equals(res) && res.isEmpty()) {
            return rpCodes;
        }
        Rp rp = JSONObject.parseObject(res, Rp.class);
        if (rp.getHotelGoods() == null) {
            return rpCodes;
        }
        List<HotelGoods> list = rp.getHotelGoods();
        if (list.isEmpty()) {
            return rpCodes;
        }
        for (HotelGoods good : list) {
            List<Goods> goodsListoods = good.getGoods();
            if (goodsListoods.isEmpty()) {
                return rpCodes;
            }
            for (Goods goods : goodsListoods) {
                if (goods.getGoodsName() != null && (goods.getGoodsStatus() == 1 || goods.getGoodsStatus() == 0)) {
                    String goodsName = screenString(goods.getGoodsName());
                    if ("".equals(goodsName)) {
                        goodsName = "全额预付";
                    }
                    if (goodsName.contains("连住") || goodsName.contains("学生")) {
                        continue;
                    }
                    HtSellRoom htLogicRoom = new HtSellRoom();
                    Long realRoomCode = goods.getRoomInfoList().get(0).getRealRoomId();
                    if (realRoomCode == null) {
                        continue;
                    }
                    //房型ID。
                    htLogicRoom.setRoomCode(realRoomCode);
                    if (listRoom.contains(realRoomCode)) {
                        Long rpCode = goods.getGoodsId();
                        //	产品ID
                        htLogicRoom.setRpCode(rpCode);
                        rpCodes.add(rpCode);
                        //酒店ID
                        htLogicRoom.setHotelCode(pushHotelBody.getHotelId());
                        htLogicRoom.setId(goods.getGoodsId());
                        //产品名称
                        htLogicRoom.setRpName(goodsName.length() < 299 ? goodsName : goodsName.substring(0, 299));
                        //	是否需要用户真实手机号
                        htLogicRoom.setIsPhone(goods.getNeedRealTel());
                        //	房态：,0 满房,1 可预订,2 不可预订,3 不展示
                        htLogicRoom.setRpStatus(1);
                        //	免费早餐数，breakfastType=1时非空
                        List<Breakfast> breakfastList = goods.getBreakfast();
                        Map<String, Object> breakfastMap = this.breakfast(breakfastList);
                        String breakfastCals = (String) breakfastMap.get("breakfastCals");
                        int breakfastNum = (int) breakfastMap.get("breakfastNum");
                        htLogicRoom.setBreakfastNum(breakfastNum);
                        htLogicRoom.setBreakfastCal(breakfastCals);
                        //支付方式 0：预付，2：现付非担保  数据库： 支付类型，只支持：1：预付5：现付6: 信用住7:在线预约8:在线预约信用住。其中5,6,7,8三种类型需要申请权限
                        if (goods.getPaymentType() != 0) {
                            continue;
                        }
                        htLogicRoom.setPaymentType(1);
                        Map<String, Object> bookRuleMap = bookRule(goods.getBookRules());
                        Integer minDay = Integer.parseInt(bookRuleMap.get("minDays").toString());
                        Integer maxDay = Integer.parseInt(bookRuleMap.get("maxDays").toString());
                        Integer minBookHour = Integer.parseInt(bookRuleMap.get("minBookHours").toString());
                        Integer maxBookHour = Integer.parseInt(bookRuleMap.get("maxBookHours").toString());
                        //连续入住最少天数，0表示不限制
                        htLogicRoom.setMinDays(minDay);
                        //	连续入住最多天数，0表示不限制
                        htLogicRoom.setMaxDays(maxDay);
                        //最早预订时间，格式为HH:mm:ss, 空值表示不限制。
                        htLogicRoom.setMinHours(minBookHour);
                        //最晚预订时间，格式为HH:mm:ss, 空值表示不限制
                        htLogicRoom.setMaxHours(maxBookHour);
                        //规则生效开始日期，0表示默认生效规则；如：20190209，表示该规则2019年2月9号开始生效 新增
                        //规则生效结束日期，0表示默认生效规则；如：20190210，表示该规则2019年2月10号结束 新增
                        if (goods.getBookRules().size() > 0) {
                            Integer starTime = goods.getBookRules().get(0).getInStartDate();
                            Integer endTime = goods.getBookRules().get(0).getInEndDate();
                            if (starTime != 0 && endTime != 0) {
                                try {
                                    htLogicRoom.setStartTime(DateUtils.format(new SimpleDateFormat("yyyyMMdd").parse(starTime.toString())));
                                    htLogicRoom.setEndTime(DateUtils.format(new SimpleDateFormat("yyyyMMdd").parse(endTime.toString())));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        htLogicRoom.setCancelPolicy(cancelRule(goods.getCancelRules()));
                        htLogicRooms.add(htLogicRoom);
                    }
                }
            }
        }
        if (htLogicRooms.size() != 0) {
            htLogicRoomService.saveOrUpdateBatch(htLogicRooms);
        }
        return rpCodes;
    }

    /**
     * 接收美团返回值
     *
     * @param data
     * @param method
     * @return
     */
    private String result(JSONObject data, String method, Map<String, Object> map) {
        FxBaseApiRequest fxBaseApiRequest = new FxBaseApiRequest();
        fxBaseApiRequest.setPartnerId(Integer.valueOf(map.get("partnerId").toString()));
        fxBaseApiRequest.setAccesskey(map.get("accessKey").toString());
        fxBaseApiRequest.setSecretKey(map.get("secretKey").toString());
        fxBaseApiRequest.setMethod(method);
        fxBaseApiRequest.setData(data.toJSONString());
        String result = new MtClient().post(fxBaseApiRequest);
        JSONObject hotelData = JSONObject.parseObject(result);
        if (!(hotelData.getInteger("code").equals(0))) {
            log.error("请求美团返回结果：{}", result);
        }
        return hotelData.getString("result");
    }


    @Override
    public void rates(PushHotelBody pushHotelBody, List<Long> rpCodes, Map<String, Object> map) {
        if (rpCodes.isEmpty()) {
            return;
        }
        List<HtDailyRoom> htDailyrooms = new ArrayList<>();
        //请求参数hotel.goods.price
        JSONObject data = new JSONObject();
        ArrayList<Long> hotelIds = new ArrayList<>();
        hotelIds.add(pushHotelBody.getHotelId());
        Map<String, Object> mapDate = date();
        data.put("hotelIds", hotelIds);
        data.put("startDate", mapDate.get("startDate"));
        data.put("endDate", mapDate.get("endDate"));
        //接收返回值
        String resPrice = this.result(data, "hotel.goods.price", map);
        Price price = JSONObject.parseObject(resPrice, Price.class);
        List<GoodsPrices> listgoodsPrices = price.getGoodsPrices();
        for (GoodsPrices goodsPrices : listgoodsPrices) {
            Long rpCode = goodsPrices.getGoodsId();
            if (!rpCodes.contains(rpCode)) {
                continue;
            }
            List<PriceModels> priceModels = goodsPrices.getPriceModels();
            for (PriceModels priceModel : priceModels) {
                HtDailyRoom htDailyroom = new HtDailyRoom();
                htDailyroom.setRpCode(rpCode.toString());
                htDailyroom.setDate(DateUtils.format(priceModel.getDate()));
                htDailyroom.setPrice((priceModel.getSalePrice()));
                htDailyroom.setSubPrice(priceModel.getSubPrice());
                htDailyrooms.add(htDailyroom);
            }
        }
        this.resultStatus(pushHotelBody.getHotelId(), htDailyrooms, map);
    }

    /**
     * 拉取酒店房态
     *
     * @param hotelId
     * @param htDailyrooms
     */
    private void resultStatus(Long hotelId, List<HtDailyRoom> htDailyrooms, Map<String, Object> map) {
        //请求参数hotel.goods.status
        JSONObject dataStatus = new JSONObject();
        dataStatus.put("hotelId", hotelId);
        Map<String, Object> mapDate = date();
        dataStatus.put("checkinDate", mapDate.get("startDate"));
        dataStatus.put("checkoutDate", mapDate.get("endDate"));
        dataStatus.put("goodsType", 1);
        //接收返回值
        String resStatus = result(dataStatus, "hotel.goods.status", map);
        Status status = JSONObject.parseObject(resStatus, Status.class);
        List<GoodsStatuses> listGoodsStatuses = status.getGoodsStatuses();
        for (GoodsStatuses goodsStatuses : listGoodsStatuses) {
            for (HtDailyRoom htDailyroom : htDailyrooms) {
                if (htDailyroom.getRpCode().equals(goodsStatuses.getGoodsId().toString())) {
                    List<GoodsStatus> listGoods = goodsStatuses.getGoodsStatuses();
                    for (GoodsStatus goodsStatus : listGoods) {
                        if (DateUtils.format(goodsStatus.getDate()).equals(htDailyroom.getDate())) {
                            int num = 0;
                            int intStatus = goodsStatus.getStatus();
                            if (intStatus == 1) {
                                num = 2;
                                htDailyroom.setStatus(intStatus);
                            } else {
                                htDailyroom.setStatus(0);
                            }

                            htDailyroom.setSaleNum(num);
                            break;
                        }
                    }
                }
            }
        }
        redisUtil.saveOrUpdateBatchRates(htDailyrooms);
    }

    /**
     * 拉取全部酒店ID
     *
     * @return
     */
    @Async
    @Override
    public void repeat(Integer dtId) {
        //创建任务
        Integer taskCode = Integer.valueOf(System.currentTimeMillis() / 1000 + "");
        OpTaskStatus opTaskStatus = new OpTaskStatus();
        opTaskStatus.setTaskName(Constant.Task.HOTEL_ALL_PULL.getName());
        opTaskStatus.setStartTime(new Date());
        opTaskStatus.setTaskCode(taskCode);
        opTaskStatus.setDtId(dtId);
        opTaskStatusService.save(opTaskStatus);
        List<DtOrderChannels> dtOrderChannelsEntities = dtOrderChannelsService.getByPriority();
        List<InitBody> initList = new ArrayList<>();
        for (DtOrderChannels dtOrderChannelsEntity : dtOrderChannelsEntities) {
            maxIds = 0L;
            Map<String, Object> map = new HashMap<>();
            Integer partnerId = dtOrderChannelsEntity.getPartnerId();
            String secretKey = dtOrderChannelsEntity.getSecret();
            String accessKey = dtOrderChannelsEntity.getAccessKey();
            map.put("partnerId", partnerId);
            map.put("secretKey", secretKey);
            map.put("accessKey", accessKey);
            while (maxIds != -1) {
                List<Long> longList = getHotelIds(maxIds, map);
                for (Long hotelId : longList) {
                    InitBody initBody = new InitBody();
                    initBody.setAccessKey(accessKey);
                    initBody.setHotelId(hotelId);
                    initBody.setPartnerId(partnerId);
                    initBody.setSecretKey(secretKey);
                    initList.add(initBody);
                }
            }
        }
        OpTaskStatus opTask = new OpTaskStatus();
        opTask.setTotal(initList.size());
        opTaskStatusService.getBaseMapper().update(opTask, new UpdateWrapper<OpTaskStatus>().eq("task_code", taskCode));
        // 任务结束标识
        InitBody end = new InitBody();
        end.setHotelId(-1L);
        initList.add(end);
        //将酒店Id放入rabbitmq队列
        for (InitBody initBody : initList) {
            initBody.setTaskId(opTaskStatus.getTaskCode());
            //将消息发送到“INIT”队列中
            sendMsg.execute(Constant.RabbitMq.INIT, 1, initBody);
        }
    }

    /**
     * 拉取酒店ID
     *
     * @param maxId
     * @return
     */
    private List<Long> getHotelIds(Long maxId, Map<String, Object> map) {
        //请求参数hotel.poi.list
        JSONObject dataStatus = new JSONObject();
        dataStatus.put("maxId", maxId);
        dataStatus.put("pageSize", 1000);
        InitBody initBody = new InitBody();
        initBody.setPartnerId(Integer.valueOf(map.get("partnerId").toString()));
        initBody.setAccessKey(map.get("accessKey").toString());
        initBody.setSecretKey(map.get("secretKey").toString());
        String res = result(dataStatus, "hotel.poi.list", map);
        JSONObject hotelIds = JSONObject.parseObject(res);
        JSONArray htIds = hotelIds.getJSONArray("hotelIds");
        List<Long> longList = htIds.toJavaList(Long.class);
        maxIds = hotelIds.getLong("maxId");
        return longList;
    }

    /**
     * 筛选出字符串
     *
     * @param str
     * @return
     */
    private String screenString(String str) {
        String regex = "[\\u4E00-\\u9FA5A-Za-z0-9]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        StringBuilder string = new StringBuilder();
        while (matcher.find()) {
            string.append(matcher.group(0));
        }
        return string.toString();
    }

    /**
     * 预定政策
     *
     * @param bookRulesList
     * @return
     */
    private Map<String, Object> bookRule(List<BookRules> bookRulesList) {
        Map<String, Object> map = new HashMap<>();
        int minDays = 1;
        int maxDays = 90;
        int minBookHours = 0;
        int maxBookHours = 720;
        // 为空默认值
        if (bookRulesList != null && !bookRulesList.isEmpty()) {
            for (BookRules bookRules : bookRulesList) {
                Integer start = bookRules.getInStartDate();
                Integer end = bookRules.getInEndDate();
                Date nowDate = new Date();
                Date startDate = DateUtils.addDateDays(nowDate, -1);
                Date endDate = DateUtils.addDateYears(nowDate, 1);
                if (start != 0) {
                    startDate = DateUtils.stringToDate(DateUtils.dateChange(start.toString()), DateUtils.DATE_PATTERN);
                }
                if (end != 0) {
                    endDate = DateUtils.stringToDate(DateUtils.dateChange(end.toString()), DateUtils.DATE_PATTERN);
                }
                assert startDate != null;
                if (DateUtils.isEffectiveDate(nowDate, startDate, endDate)) {
                    Integer bookDaysEarliest = bookRules.getEarliestBookingDays();
                    if (bookDaysEarliest != null && bookDaysEarliest != 0 && bookDaysEarliest != -1) {
                        maxBookHours = 24 * bookDaysEarliest;
                    }
                    String bookHoursEarliest = bookRules.getEarliestBookingHours();
                    if (bookHoursEarliest != null) {
                        maxBookHours += 24 - Integer.parseInt(bookHoursEarliest.substring(0, 2));
                    }
                    Integer bookDaysLatest = bookRules.getLatestBookingDays();
                    if (bookDaysLatest != null && bookDaysLatest != -1 && bookDaysLatest != 0) {
                        minBookHours = 24 * bookDaysLatest;
                    }
                    break;
                }
            }
        }
        map.put("minDays", minDays);
        map.put("maxDays", maxDays);
        map.put("minBookHours", minBookHours);
        map.put("maxBookHours", maxBookHours);
        return map;
    }

    /**
     * 退改政策
     * {"cancelPolicyType":2} 不可取消
     * {"cancelPolicyType":1} 任意取消
     * {"cancelPolicyType":5,"policyInfo":{"timeBefore":6}}表示从入住日24点往前推至少6个小时即入住日18点前可免费取消
     *
     * @param cancelRulesList List<CancelRules>
     * @return String
     */
    private String cancelRule(List<CancelRules> cancelRulesList) {
        JSONObject cancelPolicy = new JSONObject();
        // 默认不可取消
        cancelPolicy.put("cancelPolicyType", 2);
        if (cancelRulesList != null && !cancelRulesList.isEmpty()) {
            CancelRules cancelRules = cancelRulesList.get(0);
            Integer cancelType = cancelRules.getCancelType();
            Integer aheadCancelDays = cancelRules.getAheadCancelDays();
            Integer deductType = cancelRules.getDeductType();
            String aheadCancelHours = cancelRules.getAheadCancelHours();
            if (cancelType == 1 && aheadCancelDays != null && deductType != null && aheadCancelHours != null) {
                int hours;
                if (deductType == 0) {
                    hours = 24 - Integer.parseInt(aheadCancelHours.substring(0, 2));
                } else {
                    hours = Integer.parseInt(aheadCancelHours);
                }
                hours += 24 * aheadCancelDays;
                cancelPolicy.put("cancelPolicyType", 5);
                JSONObject policyInfo = new JSONObject();
                policyInfo.put("timeBefore", hours);
                cancelPolicy.put("policyInfo", policyInfo);
            }
        }
        return JSONObject.toJSONString(cancelPolicy);
    }

    /**
     * 早餐
     *
     * @param breakfasts List<Breakfast>
     * @return Map<String, Object>
     */
    private Map<String, Object> breakfast(List<Breakfast> breakfasts) {
        Map<String, Object> map = new HashMap<>();
        int breakfastNum = 0;
        JSONObject breakfastCal = null;
        List<JSONObject> breakfastCals = new ArrayList<>();
        if (breakfasts != null && !breakfasts.isEmpty()) {

            Breakfast breakfast = breakfasts.get(0);
            Integer breakfastType = breakfast.getBreakfastType();
            if (breakfastType == 1) {
                // 统一早餐
                breakfastNum = breakfast.getBreakfastNum();
                for (Breakfast b : breakfasts) {
                    // 日历早餐
                    Integer breakfastNumCal = b.getBreakfastNum();
                    Integer startDate = b.getInStartDate();
                    Integer endDate = b.getInEndDate();
                    if (startDate != 0 && endDate != 0) {
                        breakfastCal = new JSONObject();
                        breakfastCal.put("startDate", DateUtils.dateChange(startDate.toString()));
                        breakfastCal.put("endDate", DateUtils.dateChange(endDate.toString()));
                        breakfastCal.put("breakfast_count", breakfastNumCal);
                        breakfastCals.add(breakfastCal);
                    }
                }
            }
        }
        map.put("breakfastNum", breakfastNum);
        if (!breakfastCals.isEmpty()) {
            map.put("breakfastCals", JSONObject.toJSONString(breakfastCals));
        }
        return map;
    }

    /**
     * 获取最近30天日期
     *
     * @return
     */
    private Map<String, Object> date() {
        Map<String, Object> map = new HashMap<>();
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = sbf.format(d);
        Date date = DateUtils.addDateDays(DateUtils.stringToDate(sbf.format(d), DateUtils.DATE_PATTERN), 30);
        String endDate = DateUtils.format(date);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        return map;
    }

}
